<template>
  <div class="mine-layout pt-3">
    <MaProTable
      ref="proTableRef"
      :options="options"
      :schema="schema"
      :key="keykeye"
    >
      <template #toolbarLeft>
        <el-button
          type="primary"
          @click="() => {  maDialog.setTitle('添加'); maDialog.open({ formType: 'add' });  }"
        >添加</el-button>
      </template>
    </MaProTable>
    <component :is="maDialog.Dialog">
      <template #default="{ formType, data }">
        <!-- 新增、编辑表单 -->
        <el-form ref="userForm" :model="userModel" v-model="userModel" label-width="80px"  >
          <el-form-item label="渠道名称" prop="name" :rules="[{ required: true, message: '请输入', trigger: 'blur', }]" >
            <el-input v-model="userModel.name" />
          </el-form-item>
          <el-form-item label="渠道类型" prop="name" :rules="[{ required: true, message: '请输入', trigger: 'change', }]">
            <el-select v-model="userModel.type" placeholder="请选择">
              <el-option :label="item.name" :value="item.id" v-for="item in dockingMenuTypeData().dockList" :key="item.id" />
            </el-select>
          </el-form-item>
          <tabs :items="tabsList" v-model="activeName"/>
          <template v-if="activeName === '1'">
            <el-form-item label="地址" prop="url">
              <el-input v-model="userModel.url" />
            </el-form-item>
            <el-form-item label="APPID" prop="pay_userid">
              <el-input v-model="userModel.pay_userid" />
            </el-form-item>
            <el-form-item label="密钥" prop="pay_password">
              <el-input v-model="userModel.pay_password" />
            </el-form-item>
            <el-form-item label="账号" prop="username">
              <el-input v-model="userModel.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="userModel.password" />
            </el-form-item>
          </template>
          <template v-if="activeName === '2'" v-for="item in dockingMenuTypeData().otherConf"  :key="item.conf_type">
            <el-form-item :label="item.conf_title" prop="xxx"  v-if="item.conf_type==='radio'" label-width="150px" >
              <el-radio-group v-model="userModel.radio">
                <el-radio v-for="(children,i) in item.item" :key="children.conf_val"
                          @change="userModel.radioData=children"
                          :label="children.conf_title" :name="children.conf_key" />
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="item.conf_title" prop="xxx"  v-if="item.conf_type==='checkbox'" label-width="150px" >
              <el-checkbox-group v-model="userModel.checkList">
                <el-checkbox
                  v-for="children in item.item" :key="children.conf_val"
                  :label="children.conf_title" :value="children.conf_key" />
              </el-checkbox-group>
            </el-form-item>
          </template>
        </el-form>
      </template>
    </component>

    <component :is="dockingDrawer.Drawer">
      <template #default="{ formType, data }">
        <div style="display:flex;">
          <div class="box-L">
            <div>
              <el-button type="primary" >展开</el-button>
              <el-button type="primary" >全选</el-button>
              <el-dropdown trigger="click" style="margin-left:10px">
                <el-button type="primary" >
                  批量对接
                  <ma-svg-icon name="icons8:angle-down" />
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu >
                    <el-dropdown-item v-for="item in dropdownList" :key="item.value">
                      {{ item.label }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                  
                </template>
              </el-dropdown>
              <el-divider />
              <el-input placeholder="输入关键字进行过滤" v-model="filterText" />
            </div>
            <el-tree
              style="max-width: 600px"
              :props="{
                 label: 'name',
                 children: 'children',
              }"
              :data="[]"
              show-checkbox
              @check-change="handleCheckChange"
              :filter-node-method="filterNode"
            />
          </div>
          <div class="box-R">

            <MaProTable
              ref="proTableRef2"
              :options="options2"
              :schema="schema2"
              @search-submit="(form: any) => {
                console.log( JSON.stringify(form),'form搜索')
              }"
            >
              <template #toolbarLeft>
                <el-button
                  type="primary"
                  @click=" () => {
                      treeDialog.setTitle('商品对接')
                      treeDialog.open({ formType: 'product', ids: [] })
                    }
                  "
                >
                  批量对接
                </el-button>
              </template>
            </MaProTable>

          </div>
        </div>

      </template>
    </component>


    <!--    分类，商品对接-->
    <component :is="treeDialog.Dialog">
      <template #default="{ formType, ids }">
        <!-- 新增、编辑表单 -->
        <ma-form ref="treeForm" v-model="treeModel" >
          <el-form-item label="商品目录" prop="name">
            <!--           对接商品需要选择目录-->
            <el-cascader v-model="treeModel.value" :options="[]" @change="handleChange" />
          </el-form-item>
          <el-form-item label="加价模版" prop="name">
            <el-select v-model="treeModel.value" placeholder="请选择">
              <el-option label="测试" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="图片保存" prop="name">
            <el-radio-group v-model="treeModel.radio1">
              <el-radio value="1">取对方地址</el-radio>
              <el-radio value="2">自定义图片</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="自定义图片" prop="img" v-if="treeModel.radio1==='2'">
            <ma-upload-image v-model="treeModel.img" />
          </el-form-item>
        </ma-form>

      </template>
    </component>

  </div>
</template>
<script setup lang="tsx">
import {onMounted, ref ,reactive,watch} from "vue"
import {getDockList,getDockingUserInfo,categoryedit} from '~/base/api/product.ts'
import type {
  MaProTableExpose,
  MaProTableOptions,
  MaProTableSchema,
} from "@mineadmin/pro-table";
import type { Ref } from "vue";
import type { UseDialogExpose } from "@/hooks/useDialog.ts";

import {deleteByIds} from "~/base/api/user";
import {getSearchItems,getSearchItems2,dockingMenuTypeData} from "./getSearchItems.tsx";
import {getTableColumns2} from "./getTableColumns.tsx";
import useDialog from "@/hooks/useDialog.ts";
import useDrawer from "@/hooks/useDrawer.ts";
import { useMessage } from "@/hooks/useMessage.ts";
import { ResultCode } from "@/utils/ResultCode.ts";
import tabs from "@/components/y-tabs/index.vue";
defineOptions({ name: "permission:user" });

const proTableRef = ref<MaProTableExpose>() as Ref<MaProTableExpose>;
const userForm = ref();
const selections = ref<any[]>([]);
const msg = useMessage();
let activeName = ref<any>("1");
const userModel = ref<any>({})
const tabsList = reactive([
  {
    label: "基础配置",
    name: "1",
  },
  {
    label: "同步配置",
    name: "2",
  },
]);
console.log(dockingMenuTypeData(),'dockingMenuTypeData')
const filterText = ref<any>('')
const treeRef = ref<any>()
const dropdownList = reactive([
  {
    label: "一键对接",
    value: "1-1",
    index: 1
  },
  {
    label: "克隆分类",
    value: "1-2",
    index: 2
  },
  {
    label: "一键自营",
    value: "1-3",
    index: 3
  },
])
const treeModel = ref<any>({})

// 弹窗配置
const maDialog: UseDialogExpose = useDialog({
  lgWidth: "750px",
  // 保存数据
  ok: ({ formType }, okLoadingState: (state: boolean) => void) => {
        console.log(userModel.value.radioData)
        console.log(userModel.value.checkList)
    let arr: any = []
    if (userModel.value.radioData) {
      arr.push(userModel.value.radioData)
    }
    dockingMenuTypeData().otherConf.forEach((e) => {

      if (e.conf_type === 'checkbox') {
        e.item.forEach((f)=>{
          if(userModel.value.checkList.includes(f.conf_key)){
            arr.push({
              conf_key: f.conf_key,
              conf_val: f.conf_val,
            })
          }
        })
      }
    })
    if (!userForm) return
    userForm.value.validate((valid) => {
      if (valid) {
        okLoadingState(true);
        categoryedit({
          ...userModel.value,
          otherConf: JSON.stringify(arr)
        })
          .then((res: any) => {
            res.code === ResultCode.SUCCESS ? msg.success('添加成功') : msg.error(res.message);
            maDialog.close();
            proTableRef.value.refresh();
          })
          .catch((err: any) => {
            msg.alertError(err);
          });
        okLoadingState(false);

      }
    })


  },
});
// 弹窗配置
const dockingDrawer: any = useDrawer({
  size: "90%",
});
// 弹窗配置
const treeDialog: any = useDialog({
  lgWidth: "750px",
});

const getPageList = (params = {}): Promise<any> => {
  return new Promise((resolve, reject) => {
    const res =  getDockList({})
      .then((res)=>{
        let dataList = reactive<any>([])
        res.data.data.forEach((item) => {
          getDockingUserInfo({ Docking: item.id })
            .then(({data}:any)=>{
              dataList.push({
                ...item,
                num:data.num||0
              })
            })
            .catch(()=>{
              dataList.push({
                ...item,
                num:0
              })
            })
        })
        resolve({
          data: {
            total: Number(res.data.count),
            list: dataList,
          }
        })
      })

  })
}
// 架构配置
const schema = ref<MaProTableSchema>({
  searchItems: getSearchItems(),
  // 表格列
  // tableColumns: getTableColumns(maDialog, dockingDrawer),
  tableColumns: [
    { label: 'ID', prop: 'id' },
    { label: '对接名称', prop: 'name' },
    { label: '对接平台', prop: 'type_name' },
    { label: '对接域名',
      cellRender: ({ row }) => (
        <el-link
          type="primary"
          onClick={() => {
            window.open(row.url)
          }}
        >
          {row.url}
        </el-link>
      ),},
    { label: '对接账号', prop: 'username' },
    { label: '渠道余额', prop: 'num' },
    // 操作列
    {
      type: 'operation',
      label:'操作',
      fixed: 'right',
      width: '220px',
      operationConfigure: {
        type: 'tile',
        actions: [
          {
            name: 'docking',
            text: '一键对接',
            onClick: ({ row }) => {
              dockingDrawer.setTitle('商品对接')
              dockingDrawer.open({ formType: 'docking', data: row })
            },
          },
          {
            name: 'edit',
            icon: 'material-symbols:person-edit',
            text: '编辑',
            onClick: ({ row }) => {
              userModel.value = row
              maDialog.setTitle('编辑')
              maDialog.open({ formType: 'edit', data: row })
            },
          },
          {
            name: 'del',
            icon: 'mdi:delete',
            text: '删除',
            onClick: ({ row }, proxy: MaProTableExpose) => {
              msg.delConfirm('是否删除').then(async () => {
                const response = await deleteByIds([row.id])
                if (response.code === ResultCode.SUCCESS) {
                  msg.success('删除成功')
                  proxy.refresh()
                }
              })
            },
          }
        ],
      },
    },
  ],
});
// 参数配置
const options = ref<MaProTableOptions>({
  // 表格距离底部的像素偏移适配
  adaptionOffsetBottom: 210,
  header: { show: false },
  // 表格参数
  tableOptions: {
    on: {
      // 表格选择事件
      onSelectionChange: (selection: any[]) => (selections.value = selection),
    },
  },
  // 搜索参数
  searchOptions: { fold: true},
  // 搜索表单参数
  searchFormOptions: { labelWidth: "90px" },
  // 请求配置
  requestOptions: {
    api: getPageList,
  },
});


// 参数配置2
const options2 = ref<MaProTableOptions>({
  // 表格距离底部的像素偏移适配
  adaptionOffsetBottom: 210,
  header: { show: false },
  // 表格参数
  tableOptions: {
    on: {
      // 表格选择事件
      onSelectionChange: (selection: any[]) => (selections.value = selection),
    },
  },
  // 搜索参数
  searchOptions: { fold: true},
  // 搜索表单参数
  searchFormOptions: { labelWidth: "90px" },
  // 请求配置
  requestOptions: {
    api: '',
  },
});

// 架构配置
const schema2 = ref<MaProTableSchema>({
  // 搜索项
  searchItems: getSearchItems2(),
  // 表格列
  tableColumns: getTableColumns2(treeDialog),
});

onMounted(async () => {

})


const handleCheckChange = (
  data: any,
  checked: boolean,
  indeterminate: boolean
) => {
  console.log(data, checked, indeterminate)
}
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.label.includes(value)
}
const handleChange = (value) => {
  console.log(value)
}
// 批量删除
function handleDelete() {
  const ids = selections.value.map((item: any) => item.id);
  msg.confirm('是否删除').then(async () => {
    const response = await deleteByIds(ids);
    if (response.code === ResultCode.SUCCESS) {
      msg.success('删除成功');
      await proTableRef.value.refresh();
    }
  });
}


</script>

<style scoped lang="scss">

.box-L{
  width: 340px;
  min-height: 600px;
  border: 1px solid #e5e2e2;
  border-radius: 5px;
  margin-right: 10px;
  padding: 10px;
}
.box-R{
  width: 100%;
  border: 1px solid #e5e2e2;
  border-radius: 5px;
  margin-left: 10px;
  padding: 10px;

}

</style>
